import json

from flask import Blueprint, request

from apps.sys.model.user import User
from apps.tool import R, objs2dicts
from mtoken import TokenFactory, TOKEN_KEY

user = Blueprint('sys/user', __name__)


@user.route('get', methods=['GET'])
def user_get():
    """
    获取单个用户信息
    :return:
    """
    userId = request.args.get("id", 0)
    return R.data(User.to_dict(User.query.filter_by(id=userId).first()))


@user.route('list', methods=['GET'])
def user_list():
    """
    查询用户列表
    :return:
    """
    return R.data(objs2dicts(User.query.all()))


@user.route('save', methods=['POST'])
def user_save():
    """
    新增用户
    :return:
    """
    data = json.loads(request.get_data(as_text=True))
    u = User()
    User.dict2obj(u, data)
    print(u.to_dict())
    return R.success()


@user.route('update', methods=['POST'])
def user_update():
    """
    修改用户
    :return:
    """
    data = json.loads(request.get_data(as_text=True))
    u = User()
    User.dict2obj(u, data)
    print(u.to_dict())
    return R.success()


@user.route('remove', methods=['POST'])
def user_remove():
    """
    删除用户
    :return:
    """
    print(request.get_data(as_text=True))
    return R.success()


@user.route('login', methods=['POST'])
def user_login():
    """
    登录
    :return:
    """
    data = json.loads(request.get_data(as_text=True))
    if data.get('userName') == "admin" and data.get("password") == "123456":
        token_strategy = TokenFactory.get_instance()
        data = {
            "token": TokenFactory.create_token({}),
            "userId": 1,
            "userName": "admin",
            "realName": "张三"
        }
        token_strategy.set(data)
        return R.data(data)
    else:
        return R.fail("用户名或密码错误")


@user.route('info', methods=['GET'])
def user_info():
    """
    获取当前用户信息
    :return:
    """
    token = request.headers.get(TOKEN_KEY, "")
    token_strategy = TokenFactory.get_instance()
    return R.data(token_strategy.get(token))


@user.route('logout', methods=['GET'])
def user_logout():
    """
    退出系统
    :return:
    """
    token = request.headers.get(TOKEN_KEY, "")
    token_strategy = TokenFactory.get_instance()
    token_strategy.remove(token)
    return R.success()
